<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="活动名称" prop="activeName">
              <el-input v-model="queryParams.activeName" placeholder="请输入" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['system:activity:add']">新增</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="activityList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="活动名称" align="center" prop="activeName" />
        <el-table-column label="活动地点" align="center" prop="address" />
        <el-table-column label="活动开始时间" align="center" prop="startTime" width="180" />
        <el-table-column label="活动结束时间" align="center" prop="endTime" width="180" />
        <el-table-column label="报名截止时间" align="center" prop="regEndTime" width="180" />
        <!--        <el-table-column label="活动图片。轮播图" align="center" prop="imgUrl" />-->
        <!--        <el-table-column label="活动详情介绍" align="center" prop="introduce" />-->
        <el-table-column label="活动状态" align="center" prop="state">
          <template #default="scope">
            <dict-tag :options="module_state" :value="scope.row.state" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:activity:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:activity:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加或修改活动列对话框 -->
    <el-drawer v-model="dialog.visible" size="50%" :title="dialog.title" :direction="'rtl'" close-on-click-modal>
      <!--    <el-dialog :title="dialog.title" v-model="dialog.visible" width="650px" append-to-body>-->
      <el-form ref="activityFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="活动名称" prop="activeName">
              <el-input v-model="form.activeName" placeholder="请输入活动名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="活动地点" prop="address">
              <el-input v-model="form.address" placeholder="请输入活动地点" />
            </el-form-item>
          </el-col>
          <el-col :span="15">
            <el-form-item label="活动时间" prop="timeRange">
              <!--          <el-date-picker clearable-->
              <!--            v-model="form.startTime"-->
              <!--            type="datetime"-->
              <!--            value-format="YYYY-MM-DD HH:mm:ss"-->
              <!--            placeholder="请选择活动开始时间">-->
              <!--          </el-date-picker>-->
              <el-date-picker
                v-model="form.timeRange"
                type="datetimerange"
                range-separator="到"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="报名截止时间" prop="imgUrl">
              <el-date-picker
                v-model="form.regEndTime"
                type="datetime"
                placeholder="请选择报名截止时间"
                format="YYYY-MM-DD HH:mm:ss"
                date-format="MMM DD, YYYY"
                time-format="HH:mm"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动状态" prop="state">
              <el-radio-group v-model="form.state" style="width: 100%">
                <el-radio v-for="item in module_state" :label="item.label" :value="parseInt(item.value)"></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="活动图片" prop="imgUrlPath">
<!--              <multi-pic v-model="form.imgUrlPath" type="image"-->
<!--                         :img-list="[form.imgUrlPath]"-->
<!--                         @handle-checked="chooseImg"-->
<!--                         :upload-type="2"-->
<!--                          :num="9" :width="120" :height="120" />-->
              <single-pic :img-list="[form.imgUrlPath]" type="image" :upload-type="1"
                          :num="1" :width="120" :height="120" @handle-checked="chooseImg" />

            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="活动详情介绍" prop="introduce">
              <editor v-model="form.introduce" :min-height="150" :uploadType="7"/>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
      <!--    </el-dialog>-->
    </el-drawer>
  </div>
</template>

<script setup name="Activity" lang="ts">
import { listActivity, getActivity, delActivity, addActivity, updateActivity } from '@/api/module/activity';
import { ActivityVO, ActivityQuery, ActivityForm } from '@/api/module/activity/types';
import SinglePic from '@/components/SingleMaterial/single.vue';
import MultiPic from '@/components/SingleMaterial/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { module_state } = toRefs<any>(proxy?.useDict('module_state'));

const activityList = ref<ActivityVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const activityFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ActivityForm = {
  id: undefined,
  activeName: undefined,
  address: undefined,
  startTime: undefined,
  endTime: undefined,
  imgUrl: undefined,
  introduce: undefined,
  state: undefined,
  regEndTime: undefined,
  timeRange: []
}
const data = reactive<PageData<ActivityForm, ActivityQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    activeName: undefined,
    address: undefined,
    startTime: undefined,
    endTime: undefined,
    imgUrl: undefined,
    introduce: undefined,
    state: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询活动列列表 */
const getList = async () => {
  loading.value = true;
  const res = await listActivity(queryParams.value);
  activityList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}


const chooseImg = (data) => {
  console.log("menu chooseImg",data);
  if(data.length > 0) {
    form.value.imgUrlPath = data[0].imgUrl
    form.value.imgUrl = data[0].url;
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  activityFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ActivityVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加活动列表";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ActivityVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getActivity(_id);
  Object.assign(form.value, res.data);

  if (form.value.timeRange != undefined && form.value.timeRange.length >= 2) {
    form.value.timeRange[0] = new Date(form.value.timeRange[0]);
    form.value.timeRange[1] = new Date(form.value.timeRange[1]);
  }
  form.value.regEndTime = new Date(form.value.regEndTime);

  dialog.visible = true;
  dialog.title = "修改活动列表";
}

/** 提交按钮 */
const submitForm = () => {
  activityFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;

      console.log('form.value.timeRange', form.value.timeRange);
      if (form.value.timeRange != undefined && form.value.timeRange.length >= 2) {
        form.value.startTime = parseTime(form.value.timeRange[0]);
        form.value.endTime = parseTime(form.value.timeRange[1]);
        form.value.timeRange = [];
      }

      if(form.value.regEndTime!=undefined){
        console.log('form.value.regEndTime', form.value.regEndTime)
        form.value.regEndTime = parseTime(form.value.regEndTime);
      }

      if (form.value.id) {
        await updateActivity(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addActivity(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}


const parseTime = (date) => {
  console.log('parseTime', date)
  var year = date.getFullYear(); // 年
  var month = checkTime(date.getMonth() + 1); //月
  var day = checkTime(date.getDate()); //日
  var hour = checkTime(date.getHours()); //时
  var minutes = checkTime(date.getMinutes()); //分
  var seconds = checkTime(date.getSeconds()); //秒
  return year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds;
};

const checkTime = (i) => {
  //月日时分秒不足10时,补全0
  if (i < 10) {
    i = '0' + i;
  }
  return i;
};


/** 删除按钮操作 */
const handleDelete = async (row?: ActivityVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除活动列编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delActivity(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/activity/export', {
    ...queryParams.value
  }, `activity_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
